﻿using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.Prism.Modularity;
using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SurveillancePro.Base.Events;
using SurveillancePro.Base.Common;
using System.Diagnostics;
using CommonClass;
using System.Windows;
using EnvControlLib;
using VideoMgtModule.Views;
using VideoMgtModule.ViewModels;
using System.IO;
using Microsoft.Practices.Prism.Regions;
using InteractiveWhiteboardManagement.Base.Common;
using SurveillanceLib;
using FileLib;
using CommonBase;

namespace VideoMgtModule
{
    /// <summary>
    /// 视频管理模块
    /// </summary>
    public class VideoMgtModule : IModule
    {
        #region 常量

        private readonly string SAVEPATH_SCREENSHOT;

        private readonly IEventAggregator _eventAggregator;
        private readonly IUnityContainer _container;
        private readonly IRegionManager _regionManager;

        #endregion

        #region 构造函数

        public VideoMgtModule(IEventAggregator eventAggregator, IUnityContainer container,
            IRegionManager regionManager)
        {
            this._eventAggregator = eventAggregator;
            this._container = container;
            this._regionManager = regionManager;

            if (string.IsNullOrWhiteSpace(SurveillanceUtilities.ScreenShotPath))
                SAVEPATH_SCREENSHOT = SurveillanceUtilities.USERCONFIG_SCREENSHOTPATH_DEFAULT;
            else
                SAVEPATH_SCREENSHOT = SurveillanceUtilities.ScreenShotPath;

            FileOperation.CreatDirectory(SAVEPATH_SCREENSHOT); // 创建文件夹
        }

        #endregion

        #region 公开的方法

        /// <summary>
        /// 注册模块内的事件
        /// </summary>
        public void Subcribe()
        {
            // 接收主模块的消息(EnvUtilities)
            OpenModelEvent openEvent = _eventAggregator.GetEvent<OpenModelEvent>();
            openEvent.Subscribe(Show, ThreadOption.UIThread, true,
                x => x.ModelName == this.GetType().Name);
        }

        /// <summary>
        /// 事件回调函数
        /// </summary>
        /// <param name="arg"></param>
        public void Show(OpenModelEventArg arg)
        {
            if (string.IsNullOrWhiteSpace(arg.FunctionName))
            {
#if DEBUG
                Debug.WriteLine("无效的执行操作，请输入方法名称！");
#endif
                return;
            }

            try
            {
                switch (arg.FunctionName)
                {
                    case "RecordVideo": // 流数据录像
                        if (arg.Arg != null && arg.Arg is EnvVideoPanel)
                        {
                            _recordVideo(arg.Arg as EnvVideoPanel);
                        }
                        else
                        {
#if DEBUG
                            Debug.WriteLine("流数据录像：传入的视频窗口信息有问题！");
#endif
                            MessageBox.Show("流数据录像：视频窗口信息异常！", ConstantString.MSG_COMPANY);
                        }
                        break;
                    case "ScreenShot": // 视频窗口截图
                        if (arg.Arg != null && arg.Arg is ArgModel &&
                            (arg.Arg as ArgModel).obj1 != null && (arg.Arg as ArgModel).obj1 is EnvVideoPanel)
                        {
                            _screenShot((arg.Arg as ArgModel).obj1 as EnvVideoPanel,
                                (arg.Arg as ArgModel).obj2 as string);
                        }
                        else
                        {
#if DEBUG
                            Debug.WriteLine("视频窗口截图：传入的视频窗口信息有问题！");
#endif
                            MessageBox.Show("视频窗口截图：视频窗口信息异常！", ConstantString.MSG_COMPANY);
                        }
                        break;
                    

                    default:
                        break;
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
                MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
            }
        }

        #endregion

        #region 私有方法

        /// <summary>
        /// 流数据录像
        /// </summary>
        /// <param name="selectedPanel">当前所选视频窗口</param>
        private void _recordVideo(EnvVideoPanel selectedPanel)
        {
            if(selectedPanel.Tag != null &&
                selectedPanel.Tag is TagModel)
            {
                Window info = new Window()
                {
                    Topmost = true,
                    Width = 500,
                    Height = 230,
                    Title = "视频流录像",
                    WindowStartupLocation = WindowStartupLocation.CenterScreen,
                    Style = Application.Current.Resources.MergedDictionaries[0][Application.Current.Resources["FormWindowStyle"].ToString()] as Style,
                };

                TagModel panelTag = selectedPanel.Tag as TagModel;
                View_RecordVideo view = new View_RecordVideo();
                view.DataContext = new ViewModel_RecordVideo(info, panelTag);

                info.Content = view;
                info.Closed += (s, e) =>
                {
                    try
                    {
                        // To do Sth.
                    }
                    catch (System.Exception ex)
                    {
#if DEBUG
                        Debug.WriteLine(ex.Message);
#endif
                    }
                };
                info.ShowDialog();
            }
        }

        /// <summary>
        /// 视频窗口截图
        /// </summary>
        /// <param name="selectedPanel">当前所选视频窗口</param>
        /// <param name="saveScreenShotPath">截图保存路径</param>
        private void _screenShot(EnvVideoPanel selectedPanel, string saveScreenShotPath = null)
        {
            if (selectedPanel != null &&
                selectedPanel.Tag != null &&
                selectedPanel.Tag is TagModel &&
                (selectedPanel.Tag as TagModel).Driver_Instance != null &&
                !string.IsNullOrWhiteSpace((selectedPanel.Tag as TagModel).Panel_RealPlayHandle))
            {
                if (string.IsNullOrWhiteSpace(saveScreenShotPath))
                    saveScreenShotPath = SAVEPATH_SCREENSHOT;

                string saveScreenShotFileName = Path.Combine(saveScreenShotPath,
                    string.Format("ScreenShot_{0}.bmp", DateTime.Now.ToString("yyyyMMddHHmmss"))); // 保存的文件名称
                TagModel panelTag = selectedPanel.Tag as TagModel;

                if (panelTag.Driver_Instance.CapturePicture(panelTag.Panel_RealPlayHandle,
                    saveScreenShotFileName)) // 保存图片
                {
#if DEBUG
                    Debug.WriteLine("截图成功！");
#endif
                    AutoCloseNoticeWindow.Show(string.Format("截图成功！\n保存位置：{0}",
                        saveScreenShotFileName), 5, false);
                }
                else
                {
#if DEBUG
                    Debug.WriteLine("截图失败！");
#endif
                    MessageBox.Show("截图失败！", ConstantString.MSG_COMPANY);
                }
            }
        }

        #endregion

        #region IModule 成员

        public void Initialize()
        {
            Subcribe(); // 注册模块事件
        }

        #endregion
    }
}
